package com.vitabuybuy.tv.ui.shopcenter.store

import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.library.common.base.BaseFragment
import com.library.common.base.MessageModel
import com.library.common.dto.MessageEvent
import com.library.common.ext.mmkv
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.FragmentShopHomeNewBinding
import com.vitabuybuy.tv.dto.BannerDto
import com.library.common.toast.XToast
import com.library.common.util.MMKVContancts
import com.vitabuybuy.tv.adaptebinding.ImageAdapter
import com.vitabuybuy.tv.ui.WebViewActivity
import com.vitabuybuy.tv.ui.auth.LoginActivity
import com.vitabuybuy.tv.ui.shopcenter.GoodsDetailsActivity
import com.vitabuybuy.tv.ui.shopcenter.store.adapter.LiveProAdapter
import com.vitabuybuy.tv.ui.shopcenter.store.adapter.ShopCouponsListAdapter
import com.vitabuybuy.tv.ui.shopcenter.store.viewmodel.StoreHomeViewModel
import com.vitabuybuy.tv.ui.tencent.liveroom.roomutil.commondef.RoomInfo
import com.vitabuybuy.tv.ui.tencent.liveroom.ui.AudienceLiveRoomActivity
import com.vitabuybuy.tv.utils.EventCode
import kotlinx.android.synthetic.main.fragment_shop_home_new.*
import org.greenrobot.eventbus.EventBus

class StoreHomeNewFragment : BaseFragment<StoreHomeViewModel, FragmentShopHomeNewBinding>() {
    override val layoutId: Int
        get() = R.layout.fragment_shop_home_new

    private val liveProAdapter by lazy { LiveProAdapter() }
    private val couponsListAdapter by lazy { ShopCouponsListAdapter() }


    override fun initView(savedInstanceState: Bundle?) {
        mBinding.mViewModel = viewModel
        initBanner()
        rl_Product.apply {
            layoutManager = GridLayoutManager(mContext, 3)
            adapter = liveProAdapter
        }
        rcvGetCoupons.apply {
            layoutManager = LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false)
            adapter = couponsListAdapter
        }
    }

    override fun lazyLoadData() {
        val storeDetail = (parentFragment as? StoreHomeFragment)?.getStoreDetail()
        if (storeDetail != null) {
            if (storeDetail.live != null) {
                rlLiving.visibility = View.VISIBLE
                ImageAdapter.setNomalImageUrl(
                    ivLivingImage,
                    storeDetail.live.image,
                    ContextCompat.getDrawable(mContext, R.drawable.default_image)
                )
                tvLivingAudienceNumber.text =
                    String.format(getString(R.string.watch_number), storeDetail.live.viewerQuantity)
                tv_liveStauts.text = storeDetail.live.status
                tvLivingTitle.text = storeDetail.live.title
                liveProAdapter.setNewData(storeDetail.live.productList)
            } else {
                rlLiving.visibility = View.GONE
            }
            if (storeDetail.couponList.size == 0) {
                rcvGetCoupons.visibility = View.GONE
            } else {
                rcvGetCoupons.visibility = View.VISIBLE
                couponsListAdapter.setNewData(storeDetail.couponList)
            }
            viewModel.productList.value = storeDetail.productList
            my_banner.setBannerData(storeDetail.slideList)
        }

    }

    override fun observeData() {
        viewModel.liveDetils.observe(this, Observer {
            val storeDetail = (parentFragment as? StoreHomeFragment)?.getStoreDetail()
            val roomInfo = RoomInfo().apply {
                audienceCount = it.viewerQuantity
                roomID = it.roomNumber
                roomInfo = it.title
                roomName = it.title
                mixedPlayURL = it.playUrl
                storeDetail?.let {
                    roomCreator = it.id.toString()
                    authorName = it.name
                    authorId = it.id.toString()
                    authorAvatar = it.logo
                    isExecutor = false
                    attention = it.isAttention
                }
                authorRegion = storeDetail?.address
                liveId = it.id
                userId = mmkv.decodeInt(MMKVContancts.USER_ID).toString()
                userName = mmkv.decodeString(MMKVContancts.USER_NICKNAME)
                createRoom = false
            }
            AudienceLiveRoomActivity.openActivity(mContext, roomInfo)
        })
    }

    override fun eventHandling() {
        my_banner.setOnItemClickListener { _, model, view, position ->
            val bannerDto = model as BannerDto.SlideListBean
            when (bannerDto.type) {
                "page" -> {
                    WebViewActivity.openActivity(mContext, "", "", bannerDto.link as Int)
                }
                "link" -> {
                    WebViewActivity.openActivity(mContext, bannerDto.title, bannerDto.link, -1)
                }
                "product" -> {
                    GoodsDetailsActivity.openActivity(mContext, bannerDto.link.toInt())
                }
                "category" -> {
                    EventBus.getDefault().post(MessageEvent(EventCode.jump_store_cate))
                }
                "live" -> {
                }
            }
        }
        couponsListAdapter.saveCoupons = {
            if (!mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
                LoginActivity.openActivity(mContext)
            } else {
                viewModel.saveACoupon(couponsListAdapter.mData[it].id, it)
            }
        }
        rlLiving.setOnClickListener {
            if (!mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
                LoginActivity.openActivity(mContext)
                return@setOnClickListener
            }
            val storeDetail = (parentFragment as? StoreHomeFragment)?.getStoreDetail()
            viewModel.getLiveDetail(storeDetail?.live?.id)
        }
    }

    override fun onResume() {
        super.onResume()
        my_banner.startAutoPlay()
    }

    override fun onPause() {
        super.onPause()
        my_banner.stopAutoPlay()
    }

    private fun initBanner() {
        my_banner.loadImage { _, model, view, _ ->
            ImageAdapter.setNomalImageUrl(
                view as ImageView,
                (model as BannerDto.SlideListBean).image,
                ContextCompat.getDrawable(mContext, R.drawable.default_image)
            )
        }
    }


    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            3 -> {
                GoodsDetailsActivity.openActivity(
                    mContext,
                    (msg.obj as BannerDto.ProductListBean).id
                )
            }
            4 -> {
                couponsListAdapter.mData[msg.arg1].isReceived = true
                couponsListAdapter.notifyItemChanged(msg.arg1)
                XToast.success(getString(R.string.already_save_coupon))
            }
        }
    }
}
